package com.neusoft.neuiotms.dcam.workflow.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.EntityNotFoundException;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.activiti.dto.ProcessInstanceDTO;
import com.neusoft.bizcore.activiti.service.ProcessInstanceService;
import com.neusoft.bizcore.activiti.service.WorkOrderService;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.neuiotms.dcam.constant.DCAMConsts;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetLifeCycleDTO;
import com.neusoft.neuiotms.dcam.fixed.model.Asset;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetRepository;
import com.neusoft.neuiotms.dcam.fixed.service.AssetLifeCycleService;
import com.neusoft.neuiotms.dcam.fixed.service.AssetService;
import com.neusoft.neuiotms.dcam.workflow.converter.ZhuanyiSLConverter;
import com.neusoft.neuiotms.dcam.workflow.dto.ZhuanyiSLDTO;
import com.neusoft.neuiotms.dcam.workflow.model.ZhuanyiItemSL;
import com.neusoft.neuiotms.dcam.workflow.model.ZhuanyiSL;
import com.neusoft.neuiotms.dcam.workflow.repository.ZhuanyiItemSLRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.ZhuanyiSLRepository;
import com.neusoft.neuiotms.dcam.workflow.service.ZhuanyiSLService;

import io.micrometer.core.instrument.util.StringUtils;

@Service
public class ZhuanyiSLServiceImpl implements ZhuanyiSLService {

    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private ProcessInstanceService processInstanceService;
    @Autowired
    private ZhuanyiSLRepository zhuanyiSLRepository;
    @Autowired
    private ZhuanyiSLConverter zhuanyiSLConverter;
    @Autowired
    private AssetRepository assetRepository;
    @Autowired
    private AssetLifeCycleService assetLifeCycleService;
    @Autowired
    private ZhuanyiItemSLRepository zhuanyiItemSLRepository;
    @Autowired
    private AssetService assetService;

    @Override
    @Transactional
    public ZhuanyiSLDTO create(final ZhuanyiSLDTO dto, final UserBean user) {

        final String taskId = dto.getTaskId();
        final ProcessInstanceDTO instance =
                this.workOrderService.submit(dto.getTitle(), DCAMConsts.PROCESSS_ZHUANYI_SL_KEY, dto.getWorkOrderNum(),
                        user);
        dto.setTaskId(instance.getTaskId());
        dto.setWorkOrderNum(instance.getWorkorderNum());
        dto.setCreateUser(user.getUsername());
        dto.setCreateUserName(user.getName());

        // 查询当前workOrderNum和TaskId下是否存在记录
        final ZhuanyiSL oldModel = this.zhuanyiSLRepository.findByWorkOrderNumAndTaskId(
                dto.getWorkOrderNum(), taskId);
        if (oldModel == null) {
            dto.setId(null);
        }

        ZhuanyiSL model = this.zhuanyiSLConverter.toModel(dto);
        model = this.zhuanyiSLRepository.save(model);

        // 解锁以前的资产信息
        final List<ZhuanyiItemSL> all = this.zhuanyiItemSLRepository.findByMain_WorkOrderNum(dto.getWorkOrderNum());
        if (null != all) {
            this.assetService.updateLocked(all.stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                    false);
        }

        // 更新资产状态为转移中
        //        final List<String> codes = dto.getDetails().stream().map(l -> l.getCode()).distinct()
        //                .collect(Collectors.toList());
        //
        //        final List<Asset> assets = this.assetRepository.findByCodeIn(codes);
        //        final List<AssetLifeCycleDTO> lifeList = new ArrayList<>();
        //
        //        if (null != assets) {
        //            assets.forEach(l -> {
        //                final ZhuanyiItemSLDTO one =
        //                        dto.getDetails().stream().filter(s -> l.getCode().equals(s.getCode())).findFirst().get();
        //
        //                l.setLocation(one.getZhuanyiLocation());
        //                l.setLocationName(one.getZhuanyiLocationName());
        //                l.setManagementUserCode(one.getZhuanyiUserCode());
        //                l.setManagementUserName(one.getZhuanyiUserName());
        //                // 生命周期
        //                lifeList.add(AssetLifeCycleDTO.builder().code(l.getCode())
        //                        .lifeCycle(DCAMConsts.ASSET_LIFE_TYPE_ZHUANYI)
        //                        .content(l.getName() + "已转移").workNum(dto.getWorkOrderNum()).build());
        //
        //            });
        //            this.assetRepository.saveAll(assets);
        //            if (lifeList.size() > 0) {
        //                this.assetLifeCycleService.batchCreate(lifeList);
        //            }
        //        }
        // 完成当前节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);
        final ZhuanyiSLDTO result = this.zhuanyiSLConverter.toDTO(model);

        // 枷锁资产信息
        this.assetService.updateLocked(
                result.getDetails().stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                true);

        return result;
    }

    @Override
    public ZhuanyiSLDTO detail(final String workOrderNum, final String taskId, final UserBean user) {
        ZhuanyiSL model = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.zhuanyiSLRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        return new ZhuanyiSLDTO();
                    } else {
                        model = this.zhuanyiSLRepository.findByWorkOrderNumAndTaskId(workOrderNum,
                                lastTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                model =
                        this.zhuanyiSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.zhuanyiSLConverter.toDTO(model);
    }

    @Override
    public void processEnd(final String workOrderNum) {

        final ZhuanyiSL model = this.zhuanyiSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);

        // 更新资产状态为转移中
        final List<String> codes = model.getDetails().stream().map(l -> l.getCode()).distinct()
                .collect(Collectors.toList());

        final List<Asset> assets = this.assetRepository.findByCodeIn(codes);
        final List<AssetLifeCycleDTO> lifeList = new ArrayList<>();

        if (null != assets) {
            assets.forEach(l -> {
                final ZhuanyiItemSL one =
                        model.getDetails().stream().filter(s -> l.getCode().equals(s.getCode())).findFirst().get();

                l.setLocation(one.getZhuanyiLocation());
                l.setLocationName(one.getZhuanyiLocationName());
                l.setManagementUserCode(one.getZhuanyiUserCode());
                l.setManagementUserName(one.getZhuanyiUserName());
                l.setLocked(false);
                // 生命周期
                lifeList.add(AssetLifeCycleDTO.builder().code(l.getCode())
                        .lifeCycle(DCAMConsts.ASSET_LIFE_TYPE_ZHUANYI)
                        .content(l.getName() + "已转移").workNum(workOrderNum).build());

            });
            this.assetRepository.saveAll(assets);
            if (lifeList.size() > 0) {
                this.assetLifeCycleService.batchCreate(lifeList);
            }
        }
    }

}
